#include <gtest/gtest.h>
#include <filesystem>
#include "../utils/test_utils.h"

using namespace TestUtils;

class HeaderLibsTest : public ::testing::Test {
protected:
    void SetUp() override {
        cleanupBuildOutputs();
        // 设置头文件库测试需要的环境变量
        setEnvironmentVariable("BUILD_PROJECT_ROOT", std::filesystem::current_path().parent_path().string());
    }
    
    void TearDown() override {
        unsetEnvironmentVariable("BUILD_PROJECT_ROOT");
        cleanupBuildOutputs();
    }
};

TEST_F(HeaderLibsTest, HeaderLibraryBuild) {
    TestScope scope("HeaderLibraryBuild");
    
    // 构建头文件库
    auto result = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_HEADERS);
    
    // 验证构建成功
    EXPECT_EQ(result.exitCode, 0) << "Header library build failed: " << result.output;
    EXPECT_TRUE(result.containsOutput("Build completed successfully")) 
        << "Header library build success message not found";
    
    // 验证头文件库标记文件生成
    std::string headerLibFile = "out/intermediate/headers/test_headers.header_lib";
    EXPECT_TRUE(fileExists(headerLibFile)) 
        << "Header library marker file not found: " << headerLibFile;
}

TEST_F(HeaderLibsTest, HeaderLibraryStructure) {
    TestScope scope("HeaderLibraryStructure");
    
    // 验证头文件库目录结构
    std::string headerLibDir = "examples/test_header_lib";
    EXPECT_TRUE(directoryExists(headerLibDir)) 
        << "Header library directory not found: " << headerLibDir;
    
    // 验证包含目录
    std::string includeDir = headerLibDir + "/include";
    EXPECT_TRUE(directoryExists(includeDir)) 
        << "Header library include directory not found: " << includeDir;
    
    // 验证源文件目录
    std::string srcDir = headerLibDir + "/src";
    EXPECT_TRUE(directoryExists(srcDir)) 
        << "Header library src directory not found: " << srcDir;
    
    // 验证Module文件
    std::string moduleFile = headerLibDir + "/Module";
    EXPECT_TRUE(fileExists(moduleFile)) 
        << "Header library Module file not found: " << moduleFile;
}

TEST_F(HeaderLibsTest, HeaderLibraryFiles) {
    TestScope scope("HeaderLibraryFiles");
    
    // 验证头文件存在
    std::string headerFile = "examples/test_header_lib/include/test.h";
    EXPECT_TRUE(fileExists(headerFile)) 
        << "Header file not found: " << headerFile;
    
    // 验证源文件存在
    std::vector<std::string> sourceFiles = {
        "examples/test_header_lib/src/test.cpp",
        "examples/test_header_lib/src/main.cpp"
    };
    
    for (const auto& srcFile : sourceFiles) {
        EXPECT_TRUE(fileExists(srcFile)) 
            << "Source file not found: " << srcFile;
    }
}

TEST_F(HeaderLibsTest, StaticLibraryWithHeaderLib) {
    TestScope scope("StaticLibraryWithHeaderLib");
    
    // 构建依赖头文件库的静态库
    auto result = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_STATIC_LIB);
    
    // 验证构建成功
    EXPECT_EQ(result.exitCode, 0) << "Static library with header lib build failed: " << result.output;
    EXPECT_TRUE(result.containsOutput("Build completed successfully") || 
                result.containsOutput("SUCCESS")) 
        << "Static library build success message not found";
    
    // 验证静态库文件生成
    std::string staticLibPath = "out/intermediate/lib/test_static_lib/libtest_static_lib.a";
    EXPECT_TRUE(fileExists(staticLibPath)) 
        << "Static library file not found: " << staticLibPath;
}

TEST_F(HeaderLibsTest, SharedLibraryWithHeaderLib) {
    TestScope scope("SharedLibraryWithHeaderLib");
    
    // 构建依赖头文件库的动态库
    auto result = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_SHARED_LIB);
    
    // 验证构建成功
    EXPECT_EQ(result.exitCode, 0) << "Shared library with header lib build failed: " << result.output;
    EXPECT_TRUE(result.containsOutput("Build completed successfully") || 
                result.containsOutput("SUCCESS")) 
        << "Shared library build success message not found";
    
    // 验证动态库文件生成
    std::string sharedLibPath = Paths::OUT_RELEASE + "/libtest_shared_lib.so";
    EXPECT_TRUE(fileExists(sharedLibPath)) 
        << "Shared library file not found: " << sharedLibPath;
}

TEST_F(HeaderLibsTest, ExecutableWithHeaderLib) {
    TestScope scope("ExecutableWithHeaderLib");
    
    // 构建依赖头文件库的可执行程序
    auto result = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_APP);
    
    // 验证构建成功
    EXPECT_EQ(result.exitCode, 0) << "Executable with header lib build failed: " << result.output;
    EXPECT_TRUE(result.containsOutput("Build completed successfully") || 
                result.containsOutput("SUCCESS")) 
        << "Executable build success message not found";
    
    // 验证可执行文件生成
    std::string appPath = Paths::OUT_RELEASE + "/test_app";
    EXPECT_TRUE(fileExists(appPath)) 
        << "Test application not found: " << appPath;
}

TEST_F(HeaderLibsTest, HeaderLibAppRuntime) {
    TestScope scope("HeaderLibAppRuntime");
    
    // 先构建应用程序
    auto buildResult = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_APP);
    ASSERT_EQ(buildResult.exitCode, 0) << "Build failed";
    
    // 运行应用程序
    std::string appPath = Paths::OUT_RELEASE + "/test_app";
    ASSERT_TRUE(fileExists(appPath)) << "Application not found";
    
    auto runResult = executeBuildCommand(appPath);
    EXPECT_EQ(runResult.exitCode, 0) 
        << "Header lib app failed to run: " << runResult.output;
    
    // 验证应用程序输出
    EXPECT_TRUE(runResult.containsOutput("Header library test completed successfully")) 
        << "Expected header lib test output not found: " << runResult.output;
}

TEST_F(HeaderLibsTest, HeaderLibraryDependencyResolution) {
    TestScope scope("HeaderLibraryDependencyResolution");
    
    // 构建依赖头文件库的目标，验证依赖解析
    auto result = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_APP);
    
    EXPECT_EQ(result.exitCode, 0) << "Build failed";
    
    // 验证依赖分析阶段
    EXPECT_TRUE(result.containsOutput("Phase3 -- Dependency analysis")) 
        << "Dependency analysis phase not found";
    
    // 验证头文件库依赖被正确识别
    EXPECT_TRUE(result.containsOutput("test_headers")) 
        << "Header library dependency not found in output";
}

TEST_F(HeaderLibsTest, HeaderLibraryModuleConfiguration) {
    TestScope scope("HeaderLibraryModuleConfiguration");
    
    // 验证头文件库Module文件配置
    std::string modulePath = "examples/test_header_lib/Module";
    EXPECT_TRUE(fileExists(modulePath)) << "Module file not found";
    
    std::string moduleContent = readFile(modulePath);
    EXPECT_FALSE(moduleContent.empty()) << "Module file is empty";
    
    // 验证Module文件包含头文件库定义
    EXPECT_TRUE(containsString(moduleContent, "AddHeaderLibrary")) 
        << "AddHeaderLibrary not found in Module file";
    
    // 验证Module文件包含其他目标定义
    EXPECT_TRUE(containsString(moduleContent, "AddStaticLibrary")) 
        << "AddStaticLibrary not found in Module file";
    EXPECT_TRUE(containsString(moduleContent, "AddSharedLibrary")) 
        << "AddSharedLibrary not found in Module file";
    EXPECT_TRUE(containsString(moduleContent, "AddExecutable")) 
        << "AddExecutable not found in Module file";
}

TEST_F(HeaderLibsTest, HeaderLibraryIncludePaths) {
    TestScope scope("HeaderLibraryIncludePaths");
    
    // 构建头文件库后，验证包含路径设置
    auto buildResult = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_HEADERS);
    ASSERT_EQ(buildResult.exitCode, 0) << "Header library build failed";
    
    // 构建依赖头文件库的目标，验证包含路径正确
    auto appResult = executeBuildCommand(Commands::PYTHON_BUILD + " " + Targets::TEST_APP);
    EXPECT_EQ(appResult.exitCode, 0) << "App build with header lib failed: " << appResult.output;
    
    // 验证没有头文件找不到的错误
    EXPECT_FALSE(appResult.containsOutput("No such file or directory")) 
        << "Header file not found errors: " << appResult.output;
    EXPECT_FALSE(appResult.containsOutput("fatal error")) 
        << "Fatal compilation errors: " << appResult.output;
}